package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.heima.admin.mapper.UserMapper;
import com.heima.admin.service.UserService;

import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Random;

@Service
@Transactional//管理事务,异常进行回滚
public class UserServiceImpl extends ServiceImpl<UserMapper, AdUser> implements UserService {

    @Override
    public ResponseResult login(AdUserDTO dto) {
        // 1. 校验参数(用户名,密码)
        String name = dto.getName();
        String password = dto.getPassword();
        if (StringUtils.isBlank(name) || StringUtils.isBlank(password)){
            CustException.cust( AppHttpCodeEnum.PARAM_INVALID,"参数有误");
        }
        //2.根据用户名查询用户信息
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if (user==null){
            CustException.cust( AppHttpCodeEnum.PARAM_INVALID,"用户名信息不存在");
        }
        //3.对比用户输入的密码 和数据库中的密码是否一直
        String s = DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes());

        if (!user.getPassword().equalsIgnoreCase(s)){
            CustException.cust( AppHttpCodeEnum.PARAM_INVALID,"密码错误");
        }
        //4.检查用户账户状态
        if (9 != user.getStatus().intValue()){
            CustException.cust( AppHttpCodeEnum.PARAM_INVALID,"用户状态异常,请联系管理员");
        }
        //修改登陆时间
        user.setCreatedTime(new Date());
        //根据id修改信息
        this.updateById(user);
        //获得颁发的token jwt令牌
        String token = AppJwtUtil.getToken(user.getId().longValue());
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(user,adUserVO);
        //返回结果
        HashMap map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserVO);
        return ResponseResult.okResult(map);
    }
}
